﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using System.IO;

namespace Common.Tests.IO
{
 
    [TestFixture]
    public class DriveHelperTests
    {
        DriveHelper _target;

        [SetUp]
        public void Setup()
        {
            _target = new DriveHelper();
        }

        [Test]
        public void GetNextFreeDrive_does_not_return_mounted_drive()
        {
            var res = _target.GetNextFreeDrive().ToString();

            Assert.IsFalse(getDriveLettersReversed().Contains(res));
        }

        [Test]
        public void GetNextFreeDrive_does_not_return_the_same_letter_twice()
        {
            var dl0 = _target.GetNextFreeDrive().ToString();
            var dl1 = _target.GetNextFreeDrive().ToString();

            Assert.AreNotEqual(dl0, dl1, "Second call does return same drive letter!");
            Assert.IsFalse(getDriveLettersReversed().Contains(dl1));
        }

        [Test]
        public void Trigger_resync()
        {
            var dl = _target.GetNextFreeDrive();
            _target.Resynch();
            Assert.IsTrue(_target.FreeDrives.Contains(dl.ToString()));
        }

        [Test]
        public void Allow_reclaim_of_drive_letters()
        {
            var dl = _target.GetNextFreeDrive();
            _target.Reclaim(dl);
            Assert.IsTrue(_target.FreeDrives.Contains(dl.ToString()));
        }

        private List<string> getDriveLettersReversed()
        {
            var q = from d in DriveInfo.GetDrives()
                    select d.Name.Substring(0, 1).ToLower();
            return q.OrderByDescending(p => p).ToList();

            //int current = (int)'z';
            //char currentChar = Convert.ToChar(current);
            //while (q.FirstOrDefault(d => d[0] == currentChar) != null)
            //{
            //    currentChar = Convert.ToChar(++current);
            //}
            //throw new Exception("No free drive letter found!");
        }
    }
}